using System;
using System.Diagnostics;
using System.IO;

using Atomic.Libraries;
using Atomic.Libraries.Compression;

namespace Atomic.Interfaces.Yphon
{
	[Serializable]
	public static class YphonSuperfij
	{
		/// <summary>
		/// Generates the Yphon superfij.out file from OUTCAR and CONTCAR.
		/// </summary>
		public static void Generate(IBinaryData contcar, IBinaryData outcar, out IBinaryData superfij)
		{
			// Must use GNU version of awk (Debian package gawk)!
			CheckAwkVersion();

			using (TempDirectory temp = new TempDirectory())
			{
				// Don't let vasp_fij mess with the original directory. Copy input files to a temporary directory.
				File.WriteAllBytes(temp.Directory.AddFile("CONTCAR").FullName, contcar.GetData());
				File.WriteAllBytes(temp.Directory.AddFile("OUTCAR").FullName, outcar.GetData());

				Process p = new Process();
				p.StartInfo.FileName = "bash";
				p.StartInfo.WorkingDirectory = temp.Directory.FullName;
				p.StartInfo.UseShellExecute = false;
				p.StartInfo.RedirectStandardInput = true;
				p.StartInfo.RedirectStandardOutput = true;
				p.StartInfo.RedirectStandardError = true;

				// Broken pipe for some reason. Doesn't seem to affect the result.
				p.Start();
				p.StandardInput.WriteLine("export _POSIX2_VERSION=199209");
				p.StandardInput.WriteLine("vasp_fij");
				p.StandardInput.WriteLine("exit $?");
				p.StandardInput.Close();
				p.WaitForExit();

				if (p.ExitCode != 0)
				{
					throw new Exception("Failed running vasp_fij.");
				}

				superfij = CompressedData.Read(temp.Directory.AddFile("superfij.out"));
			}
		}

		private static void CheckAwkVersion()
		{
			Process p = new Process();
			p.StartInfo.FileName = "awk";
			p.StartInfo.Arguments = "-W version";
			p.StartInfo.UseShellExecute = false;
			p.StartInfo.RedirectStandardOutput = true;
			p.StartInfo.RedirectStandardError = true;

			p.Start();
			p.WaitForExit();
			string s = p.StandardOutput.ReadToEnd();

			if (p.ExitCode != 0 || s.Contains("mawk") || !s.Contains("GNU Awk"))
			{
				throw new Exception("GNU gawk must be used.");
			}
		}
	}
}
